let express = require('express');
const { insertSql } = require('../../utils');
let router = express.Router();
let connection = require('../dataBase');
const Result = require('../result');
const { log } = require('console');

function formatComment(commentList) {
  const ans = [],
    map = new Map();
  commentList.forEach((e) => {
    if (e.level === 0) ans.push(e);
    map.set(e.id, e);
    e.likeNum = e.likeNum ?? 0;
    e.dislikeNum = e.dislikeNum ?? 0;
  });
  commentList.forEach((e) => {
    if (e.level !== 0) {
      for (let com of ans) {
        if (com.id === e.parentId) {
          if (com.children) com.children.push(e);
          else com.children = [e];
          if (e.level === 2 && e.replyId) {
            e.replyAvatar = map.get(e.replyId).avatar;
            e.replyNickName = map.get(e.replyId).nickName;
          }
        }
      }
    }
  });
  return ans;
}

// 获取一篇文章的所有评论
router.get('/getAllByAid', function (req, res) {
  const { articleId, accountId } = req.query;
  let str = '`like`';
  const sql = `
  SELECT DISTINCT
	com.*,
	li.id lid,
	li.STATUS 
FROM
	(
	SELECT
		com.*,
		li.likeNum,
		li.dislikeNum 
	FROM
		(
		SELECT
			com.*,
			acc.avatar,
			acc.nickName 
		FROM
			${'`comment`'} com,
			account acc 
		WHERE
			com.articleId = ${articleId}
			AND acc.id = com.accountId 
		) com
		LEFT JOIN (
		SELECT
			commentId,
			sum( likeNum ) likeNum,
			sum( dislikeNum ) dislikeNum 
		FROM
			(
				(
				SELECT
					li.commentId,
					count( * ) likeNum,
					0 dislikeNum 
				FROM
					${str} li 
				WHERE
					li.STATUS = 0 
				GROUP BY
					li.commentId 
				) UNION ALL
				(
				SELECT
					li.commentId,
					0 likeNum,
					count( * ) dislikeNum 
				FROM
        ${str} li 
				WHERE
					li.STATUS = 1 
				GROUP BY
					li.commentId 
				) 
			) AS c 
		GROUP BY
			c.commentId 
		) li ON com.id = li.commentId 
	) com
	LEFT JOIN ( SELECT * FROM ${str} li WHERE li.accountId = ${accountId} ) li ON li.commentId = com.id 
  `;
  connection.query(sql, (err, data) => {
    if (err) {
      console.log(err);
      return new Result(res, 1200).fail();
    }
    return new Result(res, 200, formatComment(data), '获取成功').success();
  });
});

// 添加一条评论
router.post('/add', function (req, res) {
  const sql = insertSql('comment', req.body);
  connection.query(sql, (err, data) => {
    if (err) {
      return new Result(res, 1200).fail();
    }
    return new Result(res, 200, data, '添加成功').success();
  });
});

// 获取最新的评论
router.get('/public/getTop', function (req, res) {
  const sql = `
  SELECT
	com.*,acc.nickName,art.title,art.id articleId
	FROM
	${'`comment`'} com
	LEFT JOIN account acc ON com.accountId = acc.id 
	LEFT JOIN article art on com.articleId=art.id
	WHERE
	LEVEL = 0 
	ORDER BY
	com.datetime DESC 
	LIMIT 0,
	10 
  `;
  connection.query(sql, (err, data) => {
    if (err) {
      return new Result(res, 1200).fail();
    }
    return new Result(res, 200, data, '添加成功').success();
  });
});

module.exports = router;
